/*
 * Proja - project management software
 * Copyright (C) 2012  Oleg Kasian
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */
package org.proja.core.util;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

/**
 *
 * @author oleg
 */
@Repository
public class SimpleSessionDataStorage implements SessionDataStorage {

    @Autowired(required = false)
    private HttpServletRequest request;
    
    @Override
    public void add(final String key, final Object value) {
        getSession().setAttribute(key, value);
    }

    @Override
    public Object get(final String key) {
        return getSession().getAttribute(key);
    }

    @Override
    public void remove(final String key) throws IllegalArgumentException {
        if (contains(key)) {
            getSession().removeAttribute(key);
        } else {
            throw new IllegalArgumentException("Object " + key + " not bound to "
                    + "current session");
        }
    }

    @Override
    public boolean contains(final String key) {
        return getSession().getAttribute(key) != null;
    }

    @Override
    public Iterator<Entry<String, Object>> iterator() {
        final HashMap<String, Object> values = new HashMap<>();
        final Enumeration<String> names = getSession().getAttributeNames();
        while (names.hasMoreElements()) {
            final String name = names.nextElement();
            values.put(name, getSession().getAttribute(name));
        }
        return values.entrySet().iterator();
    }
    
    private HttpSession getSession() {
        return request.getSession(true);
    }

}
